import ReactDOM from 'react-dom'
import { useState, useMemo } from 'react'

type ChildProps = {
  click: () => void
}
const Child = ({ click }: ChildProps) => {
  console.log('child组件更新')
  return (
    <div style={{ backgroundColor: 'skyblue', padding: 5 }}>
      子组件：<button onClick={click}>点击</button>
    </div>
  )
}
// const Child = memo(({ click }: ChildProps) => {
//   console.log('child组件更新')
//   return (
//     <div style={{ backgroundColor: 'skyblue', padding: 5 }}>
//       子组件：<button onClick={click}>点击</button>
//     </div>
//   )
// })

type Child2Props = {
  user: { age: number }
}
const Child2 = ({ user }: Child2Props) => {
  console.log('Child2 组件更新')
  return (
    <div style={{ backgroundColor: '#abc', padding: 5 }}>
      子组件2 - 年龄： {user.age}
    </div>
  )
}
// const Child2 = memo(({ user }: Child2Props) => {
//   console.log('Child2 组件更新')
//   return (
//     <div style={{ backgroundColor: '#abc', padding: 5 }}>
//       子组件2 - 年龄： {user.age}
//     </div>
//   )
// })

const App = () => {
  const [count, setCount] = useState(0)
  const [theme, setTheme] = useState('pink')

  const handleClick = useMemo(() => {
    return () => {
      setCount(count + 10)
    }
  }, [count])

  const users = useMemo(() => {
    return {
      age: count
      // age: 19
    }
  }, [count])

  const child2 = useMemo(() => {
    return <Child2 user={{ age: count }} />
  }, [count])

  const child = useMemo(() => {
    return <Child click={handleClick} />
  }, [handleClick])

  return (
    <div style={{ backgroundColor: theme, padding: 10 }}>
      <button onClick={() => setTheme(theme === 'pink' ? 'white' : 'pink')}>
        切换主题
      </button>

      <h1>计数器：{count}</h1>
      <button onClick={() => setCount(count + 1)}>+1</button>

      <hr />

      {/* 子组件 */}
      <Child click={handleClick} />
      <div>{child}</div>
      <br />
      <Child2 user={users} />
      <div>{child2}</div>
    </div>
  )
}

ReactDOM.render(<App />, document.getElementById('root'))
